package com.skillworld.webapp.model.lesson;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.skillworld.webapp.model.util.dao.GenericDaoHibernate;

@Repository("ExamDao")
public class ExamDaoHibernate extends GenericDaoHibernate<Exam,Long> implements ExamDao
{
    private Criteria buildQuery(long courseId, List<Long> lessons)
    {
        Criteria q = getSession().createCriteria(Exam.class);
        
        q.createAlias("lesson", "l");
        
        q.add(Restrictions.eq("l.course.courseId", courseId));
        
        if(lessons != null)
        { q.add(Restrictions.in("l.lessonId", lessons)); }
        
        return  q;
    }
    
    @SuppressWarnings("unchecked")
    public List<Exam> findExams(long courseId, List<Long> lessons, int startIndex, int count)
    {
        return(List<Exam>) buildQuery(courseId, lessons)
                                .setFirstResult(startIndex)
                                .setMaxResults(count)
                                .list();
    }
    
    public long numberOfExams(long courseId, List<Long> lessons)
    {
        return(Long) buildQuery(courseId, lessons)
                        .setProjection(Projections.rowCount())
                        .uniqueResult();
    }
}
